//
//  StatusPictureView.swift
//  波波微博
//
//  Created by wave on 15/8/2.
//  Copyright © 2015年 wave. All rights reserved.
//￼

import UIKit
import SDWebImage

//选中照片给控制器发送的通知
let BBBPicCellSelectNotify = "BBBPicCellNotify"

//定义两个key值,一个URL的key,一个确定用户点击的下标
let BBBPicCellSelectUrlKey = "BBBPicUrlKey"
let BBBPicCellSelectIndexKey = "BBBPicIndexKey"

//可重用cell标识符
private let statusPictureViewCellID = "statusPictureViewCellID"

//配图视图
class StatusPictureView: UICollectionView {
    //设置模型来接受数据
        var status: Status?{
            didSet{
                sizeToFit()
                
                reloadData()
            }
        }
    
    //当我们在程序中调用sizeToFit时,会自动计算大小,也会自动调用sizeThatFits方法,
    override func sizeThatFits(size: CGSize) -> CGSize {
        
        return calcViewSize()
    }

    
    private func calcViewSize() -> CGSize{
    /*
    思路:
        1.准备常量,单张图片的大小  90 * 90  itemSize
        2.设置间距 margin
        3.每一行最多显示的图片的数量个数 rowCount = 3
    */
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        let rowCount = 3
        
        pictureLayout.itemSize = itemSize
        
        /*
        思路:
            1.根据图片的数量计算视图的大小
            2.判断图片的个数 (1张.4张.其他(2,3,5,6,7,8,9张图片))
        */
        let count = status?.pic_urls?.count ?? 0
        //没有图片
        if count == 0{
            return CGSizeZero
        }
        //1张
        if count == 1{
            //从SDWebImage获取图片缓存大小
            let key = status!.pictureURLs![0].absoluteString
            
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            
            //如果图片不在这个默认大小内
            var size = CGSize(width: 150, height: 120)
            
            //判断图图像是否存在
            if image != nil{
                size = image.size
            }

            //对图片尺寸做进一步判断,防止出现过宽过窄的情况
            size.width = size.width < 40 ? 40 : size.width
            size.width = size.width > UIScreen.mainScreen().bounds.width ? 150 : size.width
            
            pictureLayout.itemSize = size
            
            return size
        }
        //4张 是2*2的
        if count == 4{
            
            let w = itemSize.width * 2 + margin
            
            return CGSize(width: w, height: w)
        }
        //其他
        /*
        思路
            1. 计算行数
            2. 计算宽度
            3. 计算宽度
        */
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + margin * CGFloat(rowCount - 1)
        let h = itemSize.height * CGFloat(row) + margin * CGFloat(row - 1)
        
        return CGSize(width: w, height: h)
        
    }
    
    //图片布局
    private let pictureLayout = UICollectionViewFlowLayout()
    
    //构造函数,注意在这里调用父类的构造函数的之前,必须给本类的属性初始化
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: pictureLayout)
   
        backgroundColor = UIColor.whiteColor()
        
        //设置数据源,让自己当自己的数据源
        self.dataSource = self
        //设置代理
        self.delegate = self
        
        //注册可重用cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: statusPictureViewCellID)
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//在swift中,协议同样可以通过extension来写,可以将一组协议方法,放置在一起,便于代码维护和阅读
extension StatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate{

        //代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
       
        print(status?.largePicktureURLs)
        
        NSNotificationCenter.defaultCenter().postNotificationName(BBBPicCellSelectNotify,
            object: self,
            userInfo: [BBBPicCellSelectUrlKey: status!.largePicktureURLs!,
                BBBPicCellSelectIndexKey: indexPath])
        
        print("来吧,图片准备好啦!!!!!!!!!!!")
    }
    
    //数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return status?.pic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(statusPictureViewCellID, forIndexPath: indexPath) as! StatusPictureViewCell
        
        cell.imageURL = status!.pictureURLs![indexPath.item]
        
        return cell
    }
    

    
}

//在写一个class,用来懒加载控件
class StatusPictureViewCell: UICollectionViewCell{

    var imageURL: NSURL?{
        didSet{
            
            iconView.sd_setImageWithURL(imageURL!)
            
            gifImageView.hidden = ((imageURL!.absoluteString as NSString).pathExtension.lowercaseString != "gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    private func setupUI(){
    
        contentView.addSubview(iconView)
        iconView.addSubview(gifImageView)
        
        //设置自动布局
        iconView.ff_Fill(contentView)
        gifImageView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil)
    }

    //懒加载
    private lazy var iconView: UIImageView = {
    
        let img = UIImageView()
        
        img.contentMode = UIViewContentMode.ScaleAspectFill
        
        //超出边界的图片给裁掉
        img.clipsToBounds = true
        
        return img
    }()
    
    //懒加载gif标签
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))

}







